package com.ruoyi.ax.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ruoyi.ax.domain.Memo;
import com.ruoyi.ax.mapper.MemoMapper;
import com.ruoyi.ax.service.IMemoService;
import com.ruoyi.common.core.domain.VModel;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.common.utils.poi.ExcelUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.lang.reflect.Field;
import java.util.Arrays;
import java.util.List;
import java.util.Optional;

/**
 * 备忘录Service业务层处理
 *
 * @author AX
 * @date ${datetime}
 */
@Service
public class MemoServiceImpl extends ServiceImpl<MemoMapper, Memo> implements IMemoService {
    @Autowired
    private MemoMapper memoMapper;

    /**
     * 查询备忘录
     *
     * @param memoId 备忘录主键
     * @return 备忘录
     */
    @Override
    public Memo selectMemoByMemoId(Long memoId) {
        //存在用户数据越界查询，根据需要添加限制
        return memoMapper.selectById(memoId);
    }

    /**
     * 查询备忘录列表
     *
     * @param memo 备忘录
     * @return 备忘录
     */
    @Override
    public List<Memo> selectMemoList(Memo memo) {
        Long userId = SecurityUtils.getUserId();
        QueryWrapper<Memo> wrapper = new QueryWrapper<Memo>();
        wrapper.like(StringUtils.isNotEmpty(memo.getTitle()), "title", memo.getTitle());
        wrapper.like("user_id", userId);
        return memoMapper.selectList(wrapper);
    }

    /**
     * 新增备忘录
     *
     * @param memo 备忘录
     * @return 结果
     */

    @Override
    public int insertMemo(Memo memo) {
        Long userId = SecurityUtils.getUserId();
        Long deptId = SecurityUtils.getDeptId();
        memo.setUserId(userId);
        memo.setDeptId(deptId);
        memo.setCreateTime(DateUtils.getNowDate());
        return memoMapper.insert(memo);
    }

    /**
     * 修改备忘录
     *
     * @param memo 备忘录
     * @return 结果
     */
    @Override
    public int updateMemo(Memo memo) {
        memo.setUpdateTime(DateUtils.getNowDate());
        return memoMapper.updateById(memo);
    }

    /**
     * 批量删除备忘录
     *
     * @param memoIdList 需要删除的备忘录主键
     * @return 结果
     */

    @Override
    public int deleteMemoByMemoIds(Long[] memoIdList) {
        return memoMapper.deleteBatchIds(Arrays.asList(memoIdList));
    }

    /**
     * 加载所有备忘录
     *
     * @return 结果
     */
    @Override
    public List<Memo> loadAllMemo() {
        return memoMapper.selectList(null);
    }

    /**
     * 创建多条数据
     *
     * @param memo
     * @return 结果
     */
    @Override
    public int bulkInsert( Memo[] memo) {
        Long userId = SecurityUtils.getUserId();
        for (Memo m : memo) {
            m.setUserId(userId);
        }
        return saveBatch(Arrays.asList(memo)) ? 1 : 0;
    }

    /**
     * 通过excel导入数据
     *
     * @param files
     * @return
     */
    @Override
    public int importData(MultipartFile[] files) {
        MultipartFile file = files[0];
        Long userId = SecurityUtils.getUserId();
        if (null == file) return 0;
        ExcelUtil<Memo> util = new ExcelUtil<Memo>(Memo.class);
        try {
            List<Memo> memoList = util.importExcel(file.getInputStream());
            for (Memo memo : memoList) {
                memo.setUserId(userId);
            }
            return saveBatch(memoList) ? 1 : 0;
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    /**
     * 更新属性，前端-后端-数据库三向绑定
     * 用于表格快速修改参数
     *
     * @param model
     * @return 结果
     */
    @Override
    public int updateAttr(VModel model) {
        Memo obj = new Memo();
        Optional<Memo> optionalMemo = Optional.of(obj);
        Memo memo = optionalMemo.get();
        memo.setMemoId(Long.valueOf(model.getId()));
        try {
            Field field = Memo.class.getDeclaredField(model.getFieldName());
            field.setAccessible(true);
            field.set(memo, model.getModelValue());
            return memoMapper.updateById(memo);

        } catch (NoSuchFieldException e) {
            throw new RuntimeException("无法找到字段: " + model.getFieldName(), e);
        } catch (IllegalAccessException e) {
            throw new RuntimeException("无法访问字段: " + model.getFieldName(), e);
        }
    }
}
